<template>
  <div>
    <section v-if="hasCode">
      <div class="mb-1">
        <el-echarts
          theme="macarons"
          ref="chartRef"
          :height="height"
          :width="width"
          :option="chartOption"
          :loading="loading"
        ></el-echarts>
      </div>
    </section>

    <section v-else>
      <p class="text-center m-5 text-muted">没有该品类的行情数据</p>
    </section>
  </div>
</template>
<script>
import { echartsXFormatter } from '@vimi/utils-tool'

export default {
  components: {},
  props: {
    categoryCode: String,
    showChart: {
      type: String,
      default() {
        return 'month'
      },
    },
    colors: {
      type: Array,
      default() {
        return ['#8ec6ad', '#ffe']
      },
    },
    imgType: Boolean,
    width: {
      type: [Number, String],
      default: '100%',
    },
    height: {
      type: Number,
      default: 400,
    },
  },
  data() {
    return {
      loading: false,
      chartOption: {},
      optionYear: {},
      optionQuarter: {},
      optionMonth: {},
      optionDay: {},
      unit: '',
    }
  },
  computed: {
    hasCode() {
      return !!this.categoryCode
    },
  },
  watch: {
    categoryCode() {
      this.getData()
    },
    showChart(val) {
      this.changeChart(val)
    },
  },
  created() {
    this.getData()
  },
  mounted() {},
  methods: {
    async getData() {
      if (!this.hasCode) {
        return
      }

      this.loading = true
      const [res, err] = await this.$utils.promise(
        this.$api.getData('industrial_db', 'product_market_statics', {
          'category_code.eq': this.categoryCode,
        })
      )
      this.loading = false

      if (err) {
        return this.$message.error('获取市场行情失败！')
      }

      if (res && res.data && res.data.length) {
        const data = res.data[0]
        this.unit = data.unit || ''
        try {
          const dataDay = JSON.parse(data.day_json)
          const dataMonth = JSON.parse(data.month_json)
          const dataQuarter = JSON.parse(data.quarter_json)
          const dataYear = JSON.parse(data.year_json)

          // 近7年
          const year = new Date().getFullYear()
          const yearList = []
          for (let i = year - 6; i <= year; i++) {
            yearList.push(i)
          }
          this.optionYear = this.convertData('近7年市场行情', '', dataYear, yearList, '年')

          // 近4个季度
          const quarterList = []
          for (let i = 1; i <= 4; i++) {
            quarterList.push(i)
          }
          this.optionQuarter = this.convertData(
            '近4个季度市场行情',
            '',
            dataQuarter,
            quarterList,
            '季度'
          )

          // 近一年
          const monthList = []
          for (let i = 1; i <= 12; i++) {
            monthList.push(i)
          }
          this.optionMonth = this.convertData('近12个月市场行情', '', dataMonth, monthList, '月')

          // 近30天
          const dayList = []
          if (dataDay && dataDay.data && dataDay.data.length) {
            const dd = dataDay.data[0].data || []
            for (const ds of dd) {
              if (ds && ds.length > 1) {
                dayList.push(ds[1])
              }
            }
          }
          this.optionDay = this.convertData('近30天市场行情', '', dataDay, dayList, '')

          this.setOption(this.optionDay)
        } catch (e) {
          return this.$message.warning('无市场行情数据！')
        }
      } else {
        this.optionYear = { title: '近7年市场行情' }
        this.optionQuarter = { title: '近4个季度市场行情' }
        this.optionMonth = { title: '近1年市场行情' }
        this.optionDay = { title: '近30天市场行情' }
      }
    },

    convertData(title, subtext, data, list, label) {
      let legend = []
      const xData = []
      const aData = []
      const bData = []
      if (data && data.data && data.data.length > 1) {
        legend = [data.data[0].serieName, data.data[1].serieName]
        const dataA = data.data[0].data || []
        const dataB = data.data[1].data || []
        for (const i of list) {
          xData.push(`${i}${label}`)
          let ad = ''
          let bd = ''
          for (let j = 0; j < dataA.length; j++) {
            const a = dataA[j]
            if (a && a.length > 1 && (a[1] === i || Number(a[1]) === Number(i))) {
              ad = a[0]
              dataA.splice(j, 1)
            }
          }
          for (let k = 0; k < dataB.length; k++) {
            const b = dataB[k]
            if (b && b.length > 1 && (b[1] === i || Number(b[1]) === Number(i))) {
              bd = b[0]
              dataB.splice(k, 1)
            }
          }
          aData.push(ad)
          bData.push(bd)
        }
      }
      return {
        title: title,
        subtext: subtext,
        legend: legend,
        xData: xData,
        seriesDataA: aData,
        seriesDataB: bData,
      }
    },

    changeChart(type) {
      switch (type) {
        case 'day':
          this.setOption(this.optionDay)
          break
        case 'month':
          this.setOption(this.optionMonth)
          break
        case 'quarter':
          this.setOption(this.optionQuarter)
          break
        case 'year':
          this.setOption(this.optionYear)
          break
        default:
          break
      }
    },

    setOption(data = {}) {
      this.chartOption = {
        // backgroundColor: '#eff8fe',
        title: {
          text: data.title || '',
          subtext: data.subtext || '',
          right: 5,
          top: 0,
          textStyle: {
            fontSize: 14,
            color: '#333',
            fontWeight: 'bold',
          },
        },
        tooltip: {
          trigger: 'axis',
        },
        legend: {
          top: 24,
          data: data.legend || [],
          right: 5,
        },
        grid: {
          top: 60,
          left: 50,
          right: 30,
        },
        xAxis: [
          {
            type: 'category',
            data: data.xData || [],
            boundaryGap: false,
            axisLabel: {
              formatter: v => echartsXFormatter(v, 5),
            },
          },
        ],
        yAxis: [
          {
            type: 'value',
            name: `产品均价(${this.unit})`,
          },
        ],
        series: [
          {
            name: data.legend ? data.legend[0] : '',
            type: 'line',
            data: data.seriesDataA || [],
            areaStyle: {
              normal: {
                color: {
                  type: 'linear',
                  x: 0,
                  y: 0,
                  x2: 0,
                  y2: 1,
                  colorStops: this.colors.map((color, index) => {
                    return { offset: index / this.colors.length, color }
                  }),
                },
              },
            },
          },
          {
            name: data.legend ? data.legend[1] : '',
            type: 'line',
            data: data.seriesDataB || [],
            areaStyle: {
              normal: {
                color: {
                  type: 'linear',
                  x: 0,
                  y: 0,
                  x2: 0,
                  y2: 1,
                  colorStops: this.colors.map((color, index) => {
                    return { offset: index / this.colors.length, color }
                  }),
                },
              },
            },
          },
        ],
      }
    },

    resize() {
      this.$nextTick(() => {
        const { chartRef } = this.$refs
        chartRef && chartRef.resize()
      })
    },
  },
}
</script>
<style scoped></style>
